import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

# 预共享密钥和初始化向量(必须与客户端一致)
key = b'abcdefghijklmnopqrstuvwxyz123456'  # 32字节密钥
iv = b'1234567890abcdef'  # 16字节初始化向量


def decrypt_data(ciphertext):
    """解密接收到的数据"""
    try:
        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size)
        return decrypted_data.decode('utf-8')
    except Exception as e:
        print(f"解密错误: {e}")
        return None


# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定地址和端口
server_address = ('0.0.0.0', 9999)
server_socket.bind(server_address)

# 开始监听
server_socket.listen(1)
print(f"服务器正在监听 {server_address[0]}:{server_address[1]}...")

try:
    while True:
        # 接受客户端连接
        client_socket, client_address = server_socket.accept()
        print(f"接受来自 {client_address} 的连接")

        try:
            # 接收加密数据
            encrypted_data = b''
            while True:
                chunk = client_socket.recv(4096)
                if not chunk:
                    break
                encrypted_data += chunk

            # 解密数据
            decrypted_data = decrypt_data(encrypted_data)
            if decrypted_data:
                # 写入文件
                with open('received_file.txt', 'w', encoding='utf-8') as f:
                    f.write(decrypted_data)
                print("文件接收并解密成功，已保存为 received_file.txt")
            else:
                print("解密失败，未保存文件")

        except Exception as e:
            print(f"处理客户端请求时出错: {e}")
        finally:
            # 关闭客户端连接
            client_socket.close()

except KeyboardInterrupt:
    print("\n服务器关闭中...")
finally:
    # 关闭服务器套接字
    server_socket.close()